package com.xunua.NaoZiKongBai.Fragments.ShouYe;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.baoyz.widget.PullRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseDelegateMultiAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;
import com.xunua.NaoZiKongBai.Bean.ApiResponse.NewsList;
import com.xunua.NaoZiKongBai.Bean.EventBus.RefreshEvent;
import com.xunua.NaoZiKongBai.Constant;
import com.xunua.NaoZiKongBai.NewsDetailsActivity.NewsDetailsActivity;
import com.xunua.NaoZiKongBai.R;
import com.xunua.NaoZiKongBai.Utils.TimeUtil;
import com.xunua.NaoZiKongBai.Utils.log;
import com.xunua.NaoZiKongBai.View.MyJzvdStd;
import com.xunua.NaoZiKongBai.api.RetrofitApiService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jzvd.JzvdStd;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.xunua.NaoZiKongBai.Bean.ApiResponse.NewsList.DataBean.type_img;
import static com.xunua.NaoZiKongBai.Bean.ApiResponse.NewsList.DataBean.type_text;
import static com.xunua.NaoZiKongBai.Bean.ApiResponse.NewsList.DataBean.type_video;

public class NewsFragment extends RxFragment {
    @BindView(R.id.news_tv)
    TextView newsTv;
    @BindView(R.id.news_recyclerview)
    RecyclerView newsRecyclerview;
    @BindView(R.id.news_Refresh)
    PullRefreshLayout newsRefresh;

    private ShouYeFragment.NewsTypeBean typeBean;
    private Unbinder unbinder;
    private List<NewsList.DataBean> newsListBeans;
    private MyAdapter myAdapter;
    private BaseLoadMoreModule loadMoreModule;
    private int page;
    private int apage;


    public static Fragment newInstance(ShouYeFragment.NewsTypeBean typeBean) {
        NewsFragment fragment = new NewsFragment();
        fragment.typeBean = typeBean;
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        newsRecyclerview.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
            @Override
            public void onChildViewAttachedToWindow(View view) {

            }

            @Override
            public void onChildViewDetachedFromWindow(View view) {
                //修复播放视频状态时  出现其他播放异常
                MyJzvdStd jzvd = view.findViewById(R.id.newslist_videoplayer);
                if (jzvd != null) {
                    if (jzvd.state== MyJzvdStd.STATE_PLAYING) {
                        MyJzvdStd.releaseAllVideos();
                    }
                }
            }
        });
        newsRefresh.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!loadMoreModule.isLoading()) {
                    refreshList();
                }else {
                    newsRefresh.setRefreshing(false);
                }
            }
        });
        newsListBeans = new ArrayList<>();
        myAdapter = new MyAdapter();
        loadMoreModule = myAdapter.getLoadMoreModule();
        newsRecyclerview.setAdapter(myAdapter);
        myAdapter.setEmptyView(R.layout.news_loading);
        myAdapter.setAnimationEnable(true);//打开动画
        myAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);//设置动画
        loadMoreModule.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadList();
            }
        });
        page = 0;
        loadList();//加载第一页
        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                switch (adapter.getItemViewType(position)) {
                    case type_text:
                    case type_img:
                        //这个是可以跳转详情的
                        startActivity(new Intent(getActivity().getApplicationContext(), NewsDetailsActivity.class).putExtra("NewsId", newsListBeans.get(position).getNewsId()));
                        break;
                    case type_video:
                        //这个是视频的，不执行点击

                        break;
                }
            }
        });
    }

    /**
     * 刷新
     */
    private synchronized void refreshList() {
        if (!loadMoreModule.isLoading()) {
            //如果正在加载更多，那么下滑下载不会被调用
            page = 0;
            loadList();
            // 打开或关闭加载更多功能（默认为true） 当刷新的时候禁用加载更多
            loadMoreModule.setEnableLoadMore(false);
        }
    }


    private void loadList() {
        Retrofit client = new Retrofit.Builder()
                .baseUrl(Constant.wanAndroid_baseurl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        HashMap wanAndroidApiKey = Constant.getWanAndroidApiKey();
        wanAndroidApiKey.put("typeId", typeBean.getTypeid());
        apage = page;//不要在意 只是为了解决某些新闻page为0时没有数据
        if (page == 0) {
            switch (typeBean.getTypename()) {
                case "军事":
                case "时尚":
                case "NBA":
                case "股票":
                case "游戏":
                case "健康":
                case "要闻":
                    apage = 1;
                    break;
            }
        }
        wanAndroidApiKey.put("page", apage);
        client.create(RetrofitApiService.class).getNewsList(wanAndroidApiKey)
                .compose(bindUntilEvent(FragmentEvent.DESTROY_VIEW))//绑定生命周期   解决内存泄漏、程序崩溃问题
                .subscribeOn(Schedulers.io())
                .map(new Function<NewsList, NewsList>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public NewsList apply(NewsList newsList) throws Exception {
                        Iterator<NewsList.DataBean> iterator = newsList.getData().iterator();
                        ArrayList<NewsList.DataBean> arrayList = new ArrayList<>();
                        while (iterator.hasNext()) {
                            NewsList.DataBean data = iterator.next();
                            if (data.getVideoList() == null && data.getNewsId().equalsIgnoreCase("此类型无详情id")) {//equalsIgnoreCase() 方法用于将字符串与指定的对象比较，不考虑大小写。
                                iterator.remove();
                            } else {
                                if (!data.getNewsId().equalsIgnoreCase("此类型无详情id")){
                                    for (NewsList.DataBean d :
                                            myAdapter.getData()) {
                                        if (data.getNewsId().equals(d.getNewsId())) {
                                            //避免得到的下一页数据和上一页的数据有重复。
                                            iterator.remove();
                                        }
                                    }
                                }
                                try {
                                    Date date = TimeUtil.getDATE(data.getPostTime());
                                    String timeFormatText = TimeUtil.getTimeFormatText(date);
                                    data.setPostTime(timeFormatText);//转换数据格式，把他的时间转换为几天前的格式
                                } catch (Exception e) {
                                    data.setPostTime("");
                                }
                            }
                        }
                        return newsList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.DESTROY_VIEW))
                .subscribe(new Observer<NewsList>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NewsList newsList) {
                        preloadGlide(newsList.getData());//Glide预加载
                        if (page == 0) {
                            //刷新
                            MyJzvdStd.releaseAllVideos();
                            newsListBeans.clear();
                            newsListBeans.addAll(newsList.getData());
                            myAdapter.setNewInstance(newsListBeans);
                        } else {
                            //添加
                            newsListBeans.addAll(newsList.getData());
                            myAdapter.addData(newsList.getData());
                        }
                        page = apage;
                        loadMoreModule.setEnableLoadMore(true);//下拉刷新完成后，重新开启加载更多。
                        loadMoreModule.loadMoreComplete();//加载完成
                        if (newsList.getData().size() == 0) {
                            // 所有数据加载完成，调用此方法
                            // 需要重置"加载完成"状态时，请调用 setNewData()
                            //如果此页的数据 10条都与存在的重复，那么就关闭加载更多    权宜之计
                            loadMoreModule.loadMoreEnd();
                        }
                        newsRefresh.setRefreshing(false);//组件刷新完成
                        myAdapter.notifyDataSetChanged();//刷新适配器
                        ++page;//加载完成后page自增
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (!loadMoreModule.isLoading()){
                            //说明这个时候是下拉刷新在进行请求
                            newsRefresh.setRefreshing(false);//组件刷新失败
//                            Toast toast = Toast.makeText(getActivity().getApplicationContext(), "刷新失败", Toast.LENGTH_SHORT);
//                            toast.setGravity(Gravity.CENTER,0,0);
//                            toast.show();
                        }else {
                            //这是上滑加载
                            loadMoreModule.loadMoreFail();//加载出错
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void preloadGlide(List<NewsList.DataBean> dataBeans) {
        for (NewsList.DataBean data :
                dataBeans) {
            if (data.getImgList()!=null&&!data.getImgList().equals("null")){
                String imgurl = data.getImgList().toString().replace("[", "").replace("]", "").trim();
                Glide.with(getContext()).load(imgurl)
                        .diskCacheStrategy(DiskCacheStrategy.DATA).addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
//                        log.e("预加载失败");
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                        log.e("预加载完成");
                        return false;
                    }
                }).preload();
            }
        }
    }

    private class MyAdapter extends BaseDelegateMultiAdapter<NewsList.DataBean, BaseViewHolder> implements LoadMoreModule {
        public MyAdapter() {
            super();
            setMultiTypeDelegate(new BaseMultiTypeDelegate<NewsList.DataBean>() {
                public int getItemType(@NotNull List<? extends NewsList.DataBean> list, int i) {
                    NewsList.DataBean dataBean = list.get(i);
                    if (dataBean.getVideoList() != null) {
                        return type_video;
                    } else if (dataBean.getImgList() != null) {
                        return type_img;
                    } else {
                        return type_text;
                    }
                }
            });
            getMultiTypeDelegate()
                    .addItemType(type_text, R.layout.newslist_text)
                    .addItemType(type_img, R.layout.newslist_img)
                    .addItemType(type_video, R.layout.newslist_video);
        }

        @Override
        protected void convert(@NotNull BaseViewHolder baseViewHolder, NewsList.DataBean dataBean) {
            switch (baseViewHolder.getItemViewType()) {
                case type_text:
                    baseViewHolder.setText(R.id.newlist_text_tv_tile, dataBean.getTitle() + "");
                    baseViewHolder.setText(R.id.newlist_text_tv_postTime, dataBean.getPostTime() + "");
                    baseViewHolder.setText(R.id.newlist_text_tv_source, dataBean.getSource());
                    break;
                case type_img:
                    String replace = dataBean.getImgList().toString().replace("[", "").replace("]", "").trim();
                    Glide.with(getContext())
                            .load(replace)
                            .diskCacheStrategy(DiskCacheStrategy.DATA)
//                            .error() //异常时候显示的图片
                            .placeholder(R.mipmap.defaultimg) //加载成功前显示的图片
//                            .fallback() //url为空的时候,显示的图片
//                            .sizeMultiplier(0.7f)//略缩图
                            .into((ImageView) baseViewHolder.findView(R.id.newlist_img_img));
                    baseViewHolder.setText(R.id.newlist_img_tv_tile, dataBean.getTitle() + "");
                    baseViewHolder.setText(R.id.newlist_img_tv_postTime, dataBean.getPostTime() + "");
                    baseViewHolder.setText(R.id.newlist_img_tv_source, dataBean.getSource());
                    break;
                case type_video:
                    MyJzvdStd jzvideoplayer = baseViewHolder.getView(R.id.newslist_videoplayer);
                    String imageurl = dataBean.getImgList().toString().replace("[", "").replace("]", "").trim();
                    Glide.with(getContext())
                            .load(imageurl)
                            .diskCacheStrategy(DiskCacheStrategy.DATA)
//                            .sizeMultiplier(0.7f)//略缩图
                            .into(jzvideoplayer.posterImageView);
                    String videourl = dataBean.getVideoList().toString().replace("[","").replace("]","");
                    jzvideoplayer.setUp(videourl,dataBean.getTitle(), JzvdStd.SCREEN_NORMAL);
//                    jzvideoplayer.positionInList=baseViewHolder.getAbsoluteAdapterPosition();
                    break;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(RefreshEvent event) {
        String selectTypeName = event.getSelectTypeName();
        if (typeBean.getTypename().equals(selectTypeName)) {
            if (!loadMoreModule.isLoading()) {
                newsRecyclerview.scrollToPosition(0);
                newsRefresh.setRefreshing(true);
                refreshList();
            }
        }
    }
//        ((LinearLayoutManager)newsRecyclerview.getLayoutManager()).scrollToPositionWithOffset(0,0);
//         您可以通过从订户的事件处理方法中调用cancelEventDelivery （对象事件） 来取消事件传递过程 。任何进一步的事件传递将被取消，后续的订阅者将不会接收该事件。
//        if (event!=null){
//        EventBus.getDefault().cancelEventDelivery(event);


}
